package com.wolfking.web.ssoauth.controller;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wolfking.back.core.invokelink.ThreadLocalContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wolfking.back.core.bean.Dict;
import com.wolfking.back.core.bean.User;
import com.wolfking.back.core.config.SsoConfig;
import com.wolfking.back.core.exception.ExceptionMessage;
import com.wolfking.back.core.feignclient.DictFeignClient;
import com.wolfking.back.core.feignclient.SsoFeignClient;
import com.wolfking.back.core.service.SsoUserService;
import com.wolfking.back.core.util.CookieUtil;
import sun.plugin.util.UIUtil;

/**
 * 登录的controller
 * <P>
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月19日下午5:50:23
 * @版权 归wolfking所有
 */
@Controller
public class LoginController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private SsoFeignClient ssoFeignClient;

	@Autowired
	private DictFeignClient dictFeignClient;

	@Autowired
	private SsoConfig ssoConfig;

	@Autowired
	private SsoUserService ssoUserService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model, @RequestParam(required = false) String from, HttpServletRequest request,
			HttpServletResponse response) {
		User user = ssoUserService.getUser();
		if (user != null) {
			String redirect;
			if (StringUtils.isBlank(from))
				redirect = "redirect:" + ssoConfig.getSelfRootUrl() + "/main";
			else
				redirect = "redirect:" + from;
			logger.info("目前已经登录：{}", redirect);
			return redirect;
		}
		List<Dict> themes = dictFeignClient.getByType("theme").getBody();
		model.addAttribute("themes", themes);
		String theme = CookieUtil.getCookie(request, "theme");
		if (StringUtils.isBlank(theme)) {
			CookieUtil.setCookie(request, response, "theme", "default");
			model.addAttribute("currentTheme", "默认主题");
		} else {
			boolean set = false;
			for (Dict dict : themes) {
				if (dict.getValue().equals(theme)) {
					CookieUtil.setCookie(request, response, "theme", theme);
					model.addAttribute("currentTheme", dict.getLabel());
					set = true;
					break;
				}
			}
			if (!set) {
				CookieUtil.setCookie(request, response, "theme", "default");
				model.addAttribute("currentTheme", "默认主题");
			}
		}
		model.addAttribute("from", from);
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String dologin(Model model, HttpServletRequest request, HttpServletResponse response,
			@RequestParam String username, @RequestParam String password, @RequestParam(required = false) String from) {
		logger.info("username is :{}", username);
		logger.info("password is :{}", password);
		model.addAttribute("username", username);
		try {
			String tokenId = ssoFeignClient.userLogin(username, password).getBody().getTokenId();
			// 设置登录有效时间是1天
			CookieUtil.setCookie(request, response, "tokenId", tokenId, 86400);
			String redirect;
			if (StringUtils.isBlank(from))
				redirect = "redirect:" + ssoConfig.getSelfRootUrl() + "/main";
			else
				redirect = "redirect:" + from;
			logger.info("登陆后跳转：{}", redirect);
			return redirect;
		} catch (Exception e) {

			try {
				logger.error("", e);
				ExceptionMessage ex = ExceptionMessage.parse(e);
				model.addAttribute("message", ex.getMessage());
			} catch (Exception ee) {
				logger.error("", e);
				model.addAttribute("message", "登录异常");
			}

		}
		return login(model, from, request, response);
	}

	/**
	 * 用户注销
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		String tokenId = ssoUserService.getTokenId(request);
		ssoFeignClient.logout(tokenId);
		return "redirect:" + ssoConfig.getSelfRootUrl() + "/login";
	}
}
